#include "MyTable.h"
#include "../../DebugTools/DebugTool.h"
#include "HeaderSection.h"
#include "MyLineEdit.h"
#include <QtWidgets>

MyTable::MyTable(QWidget* parent)
    : QTableWidget(7, 4, parent)
{
    QSignalBlocker blocker(this);
    // 初始化，为每个单元格设置一个item,先全部不能选中
    for (int i = 0; i < rowCount(); ++i) {
        for (int j = 0; j < 4; ++j) {
            QTableWidgetItem* item = new QTableWidgetItem;
            setItem(i, j, item);
        }
    }

    // 合计行 处理
    int lastRow = rowCount() - 1;
    setSpan(lastRow, 0, 1, 2);
    item(lastRow, 0)->setForeground(Qt::black);
    item(lastRow, 0)->setFont(QFont("楷体", 14, QFont::Bold));
    item(lastRow, 0)->setText("合 计:");

    // 隐藏表头  水平和垂直
    horizontalHeader()->hide();
    verticalHeader()->hide();


    item(0, 0)->setForeground(Qt::black);
    item(0, 0)->setFont(QFont("楷体", 14, QFont::Bold));
    item(0, 0)->setText("摘  要");
    item(0, 0)->setTextAlignment(Qt::AlignCenter);

    // cell 0 1 科目代码表头
    item(0, 1)->setText("会计科目");
    item(0, 1)->setForeground(Qt::black);
    item(0, 1)->setFont(QFont("楷体", 14, QFont::Bold));
    item(0, 1)->setTextAlignment(Qt::AlignCenter);

    // cell 0 2 借方金额 表头
    auto* sec = new HeaderSection("借方金额");
    setCellWidget(0, 2, sec); //  passing the ownership

    // cell 0 3 贷方金额 表头
    sec = new HeaderSection("贷方金额");
    setCellWidget(0, 3, sec); //  passing the ownership


    // 表 设置 0，1 列的宽度
    setColumnWidth(0, 200);
    setColumnWidth(1, 500);

    // 表设置行高，2 3 列设置 借贷edit 设置宽度,并把edit的txt 传给item
    for (int i = 0; i < rowCount(); ++i) {
        setRowHeight(i, 51);
        for (int j = 0; j < columnCount(); ++j) {
            if (i > 0 && (j == 2 || j == 3)) {
                setColumnWidth(j, 189);
                auto* edt = new MyLineEdit(this);
                edt->setIndex(i, j);
                setCellWidget(i, j, edt); //  passing the ownership
                connect(edt, &MyLineEdit::editingFinished, this,&MyTable:: updateTotal);
            }
        }
    }

    // 设置第一行 不可编辑
    setEnableRow(0,false);
    // 设置第后一行 不可编辑
    setEnableRow( rowCount ()-1, false);

    this->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);

    // 设置选定行为
    setSelectionBehavior(QAbstractItemView::SelectItems);
    // 设置回车编辑
    setEditTriggers (QAbstractItemView::DoubleClicked);

    // item的数据如果变化了，就检查该行的数据
    connect(this, &QTableWidget::itemSelectionChanged, [this] {
        if(selectedItems ().isEmpty ())
            return ;

        auto *item =selectedItems ().first ();
        int row = item->row ();
        CheckRow (row);
    });
}

void MyTable::keyPressEvent(QKeyEvent *event)
{
  if(event->key () == Qt::Key_Delete   || event->key () == Qt::Key_Backspace ){

    QList<QTableWidgetItem *> lists = selectedItems();
    foreach (auto item, qAsConst(lists)) {
      item->setText ("");
    }
  }
}


bool MyTable::CheckRow(int row)
{
    bool ok = item(row, 0)->text().isEmpty(); // 第 0 列 是否空
    ok &= item(row, 1)->text().isEmpty(); // 第 1 列 是否空
    ok = !ok;
    ok &= (!item(row, 2)->text().isEmpty() ^ !item(row, 3)->text().isEmpty());
    return ok;
}

bool MyTable::RowIsEmpty(int row)
{
    for (int j = 0; j < 4; ++j) {
        bool ok = item (row,j)->text ().isEmpty ();
        if(!ok)
            return false;
    }
    return true;
}

void MyTable::setEnableRow(int row, bool enable)
{
    this->blockSignals (true);
    for (int j = 0; j < columnCount(); ++j) {
        if ( enable ) {
            item(row, j)->setFlags(Qt::ItemIsEditable | Qt::ItemIsSelectable | Qt::ItemIsEnabled);
        }else{
            item(row, j)->setFlags(Qt::NoItemFlags);
        }
        QWidget* w = cellWidget(row, j);
        if (w)
            w->setEnabled(enable);
    }
    this->blockSignals (false);
}

void MyTable::updateTotal()
{
    int i,j;
    qulonglong total = 0;
    for (j = 2; j <= 3; ++j) {
        total = 0;
        for (i = 1; i < rowCount () - 1; ++i) {
            QWidget *w = cellWidget (i,j);
            MyLineEdit *edt = (MyLineEdit *) w;
            total += edt->text ().toULongLong ();
        }
        QWidget *wt = cellWidget (rowCount ()-1,j);
        MyLineEdit *edtt = (MyLineEdit *) wt;
        edtt->setText (QString::number (total));
    }
}

QVariantList MyTable::getRowData()
{
    QVariantList mList;     // 准备写入的值
    // 写入Range的数据
    for (int i = 1; i < rowCount () -1; ++i) {
        if(item (i,0)->text ().isEmpty ())
            break;
        QVariantList tempVarRow;        // 每一行的QVariantList
        tempVarRow << item (i,0)->text ();
        tempVarRow << item (i,1)->text ();
        tempVarRow << ((MyLineEdit *)cellWidget (i,2) )->text ();
        tempVarRow << ((MyLineEdit *)cellWidget (i,3) )->text ();
        mList << QVariant(tempVarRow);  // 通过QVariant加入mList
    }
    return mList;
}
